package fatworm.server;

import java.util.HashSet;

import fatworm.metadata.*;
import fatworm.planner.*;
import fatworm.storage.buffer.*;
import fatworm.storage.file.*;
import fatworm.tx.log.*;
import fatworm.tx.*;

public class Fatworm
{
    private static MetadataMgr mdm;
    public static FileMgr fileMgr;
    public static BufferMgr bufferMgr;
    public static LogMgr logMgr;
    private static String dbname = null;
    private static HashSet<String> nameset = new HashSet<String>();
    
    static
    {
        fileMgr = new FileMgr("./Data");
        bufferMgr = new BufferMgr(1000);
        logMgr = new LogMgr("fatworm.log");
    }
    
    public static void useDB(String name) {
//        initFileLogAndBufferMgr(dirname);
    	if (dbname.equals(name))
    		return;
    	
    	dbname = name;
    	Transaction tx = new Transaction();
/*        boolean isnew = fileMgr.isNew();
        if (isnew)
           System.out.println("creating new database");
        else {
           System.out.println("recovering existing database");
           tx.recover();
        }*/
        initMetadataMgr(false, tx);
        tx.commit();
    }
    
    public static void createDB(String name) {
    	nameset.add(name);
    	dbname = name;
    	Transaction tx = new Transaction();
    	initMetadataMgr(true, tx);
    	tx.commit();
    }
    
    public static void dropDB(String name) {
    	nameset.remove(name);
    }
    
    public static String getDBName() {
    	return dbname;
    }
    
    public static void initMetadataMgr(boolean isnew, Transaction tx) {
        mdm = new MetadataMgr(isnew, tx);
    }

    public static MetadataMgr mdMgr()
    {
        return mdm;
    }
    public static Planner planner()
    {
        QueryPlanner qplanner = new BasicQueryPlanner();
        UpdatePlanner uplanner = new BasicUpdatePlanner();
        return new Planner(qplanner, uplanner);
    }
}